package com.yifei.controller.system;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yifei.annotation.RateLimiter;
import com.yifei.model.form.system.UserForm;
import com.yifei.model.query.system.UserPageQuery;
import com.yifei.model.result.PageResult;
import com.yifei.model.result.Result;
import com.yifei.model.vo.system.UserInfoVO;
import com.yifei.model.vo.system.UserPageVO;
import com.yifei.service.system.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;


/**
 * 用户信息表(SysUser)表控制层
 *
 * @author yiFei
 * @since 2023-09-23 20:56:11
 */
@Api(tags = "用户信息表(SysUser)")
@RestController
@RequestMapping("users")
public class SysUserController {
    /**
     * 用户信息表(SysUser)对象
     */
    @Autowired
    private SysUserService userService;

    @ApiOperation(value = "获取当前登录用户信息")
    @ApiImplicitParam(name = "Authorization", value = "Token", required = true, dataType = "String", paramType = "header")
    @GetMapping("/me")
    public Result<UserInfoVO> getCurrentUserInfo() {
        UserInfoVO userInfoVO = userService.getCurrentUserInfo();
        return Result.success(userInfoVO);
    }

    @ApiOperation(value = "用户分页列表")
    @ApiImplicitParam(name = "Authorization", value = "Token", required = true, dataType = "String", paramType = "header")
    @GetMapping("/page")
    public PageResult<UserPageVO> getUserPage(UserPageQuery queryParams) {
        IPage<UserPageVO> result = userService.getUserPage(queryParams);
        return PageResult.success(result);
    }

    @ApiOperation(value = "新增用户")
    @ApiImplicitParam(name = "Authorization", value = "Token", required = true, dataType = "String", paramType = "header")
    @PreAuthorize("@auth.hasPerm('sys:user:add')")
    @RateLimiter(preventDuplicate = true)
    @PostMapping
    public Result<Object> saveUser(
            @RequestBody @Valid UserForm userForm
    ) {
        boolean result = userService.saveUser(userForm);
        return Result.judge(result);
    }

    @ApiOperation(value = "用户表单数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "Token", required = true, dataType = "String", paramType = "header"),
            @ApiImplicitParam(name = "userId", value = "已经过期的Token", dataType = "String", paramType = "path", required = true)
    })
    @GetMapping("/{userId}/form")
    public Result<UserForm> getUserForm(@PathVariable Long userId) {
        UserForm formData = userService.getUserFormData(userId);
        return Result.success(formData);
    }
}

